import os
import json
from build import *

#建立全局列表
exporter = []           #写入score.json
tlabe = []           #写入header.json里的level范围

#打开本地表
with open('default.json','r',encoding = "UTF-8") as j:          #载入default.json -> mo
    mo = json.load(j)
    _CONFIG_PATH = Path('Configs/' + mo['name'] + '/config.json')          #设置config.json所在路径
    __OUTPUT_PATH = 'Export/' + mo['name']            #设置输出路径（未经过Path转义处理）
    
    #检查是否存在config.json或config.json是否为空   为空或不存在就进入创建程序
    if _CONFIG_PATH.exists() == False or os.path.getsize(_CONFIG_PATH) == 0:       
        builder()
        print("请重新执行本程序")
        exit(1)       

    with open(_CONFIG_PATH,'r',encoding = "UTF-8") as k:            #载入config.json -> mp
        mp = json.load(k)
    
    #建立folder读取循环
    for csong in mo['folder']:
        if mp['level'].get(csong['name'],False):          #如果config里没有这个键对应的难度就跳过
            name = mp['level'][csong['name']]      #把本地表的folder名转换成难度表难度名
            tlabe.append(name)          #保存输入过的难度
            if ('songs' in csong) == False:         #检测folder是否存在songs集
                csong['songs'] = []         #创建songs空集
            print(csong['name'] + '  ->  ' + name + '  ' + str(len(csong['songs'])) + '个谱面')
            for cnt in csong["songs"]:            #建立一个folder内的歌曲信息读取循环
                lsTable = {}

                #将本地folder转为难度表的难易度
                lsTable['title'] = cnt['title']
                lsTable['artist'] = cnt.get('artist',"")           #artist避免报错，如果无artist会输出""
                lsTable['level'] = name
                lsTable['md5'] = cnt['md5']
                exporter.append(lsTable)

Path(__OUTPUT_PATH).mkdir(parents=True, exist_ok=True)          #创建Export文件夹

#输出score.json
with open(Path(__OUTPUT_PATH + '/score.json'),'w',encoding = "UTF-8") as m:
    json.dump(exporter,m,ensure_ascii = False)

#输出header.json
with open(Path(__OUTPUT_PATH + '/header.json'),'w',encoding = 'UTF-8') as f:
    mingw = {'level_order':[]}
    mingw['symbol'] = mp['icon']
    for ic in tlabe:            #level去重
        if mingw['level_order'].count(ic) == 0:
            mingw['level_order'].append(ic)
    mingw['name'] = mp['name']
    mingw['data_url'] = "score.json"
    json.dump(mingw,f,ensure_ascii = False)

print("操作完成")
